package ltd.hyangyang.rpc.core.registory.zook;

import lombok.extern.slf4j.Slf4j;
import ltd.hyangyang.rpc.common.bean.RpcConfig;
import ltd.hyangyang.rpc.common.bean.RpcProperties;
import ltd.hyangyang.rpc.common.utils.PropertiesReadUtils;
import ltd.hyangyang.rpc.common.utils.SingletonFactory;
import ltd.hyangyang.rpc.core.registory.RegistryService;
import ltd.hyangyang.rpc.core.remoting.server.CustomShutdownHook;
import ltd.hyangyang.rpc.core.remoting.server.RpcServerHandler;
import ltd.hyangyang.rpc.core.remoting.server.RpcServerNetty;
import org.apache.curator.framework.CuratorFramework;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

//将当前节点的信息注册到zookeeper中
@Slf4j
public class ZookRegistryService implements RegistryService {

    RpcProperties rpcProperties;

    Integer port = 10000;

    public ZookRegistryService() throws IOException {
        rpcProperties = PropertiesReadUtils.initProperties();
    }

    //注册节点信息
    @Override
    public void registry(RpcConfig rpcConfig) throws Exception {
        //添加关闭钩子
        CustomShutdownHook customshutDownHook = SingletonFactory.getSingletonBean(CustomShutdownHook.class);
        customshutDownHook.clearAllNodes();
        String addr = rpcProperties.getAddr();
        String serviceName = rpcConfig.getServiceName();
        CuratorFramework client = CuratorUtils.init(addr);
        //注册zookeeper需要根节点，服务名，子节点（ip+port）
        String group = rpcConfig.getGroup();
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        String path = CuratorUtils.ZK_ROOT_NODE + "/" + serviceName + "/" + group + "/" + hostAddress + ":" + port;
        //注册成功
        CuratorUtils.createChildNodeNeeded(client, path);
        CuratorUtils.registryNodes.put(serviceName,path);

        log.info(path);

        //使用单例模式获取
        RpcServerNetty rpcServerNetty = SingletonFactory.getSingletonBean(RpcServerNetty.class);
//        RpcServerNetty rpcServerNetty = new RpcServerNetty();

    }
}
